package org.example.flink.code;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import java.util.Arrays;

public class HelloWorldCountUseDatasetByJava {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();
        //1.source
        DataSource<String> dataSource = environment.readTextFile("data/wordcount.txt");

        //2.transformation   alt + enter 转化为lambda表达式
        FlatMapOperator<String, String> flatMapOperator = dataSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> collector) throws Exception {
//                String[] words = line.split(" ");
//                for (String word : words) {
//                    collector.collect(word);
//                }

                Arrays.stream(line.split(" ")).forEach(word -> collector.collect(word));
            }
        });
        MapOperator<String, Tuple2<String, Integer>> mapOperator = flatMapOperator.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String word) throws Exception {
                return Tuple2.of(word, 1);
            }
        });
        AggregateOperator<Tuple2<String, Integer>> aggregateOperator = mapOperator.groupBy(0).sum(1);

        //3.sink
        aggregateOperator.print();
    }
}
